package com.enation.app.javashop.core.excel;


import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.dag.eagleshop.core.account.model.dto.base.PageDTO;
import com.dag.eagleshop.core.account.model.dto.base.ViewPage;
import com.dag.eagleshop.core.account.model.dto.withdraw.QueryWithdrawBillDTO;
import com.dag.eagleshop.core.account.model.dto.withdraw.WithdrawBillDTO;
import com.dag.eagleshop.core.account.model.enums.TradeChannelEnum;
import com.dag.eagleshop.core.account.model.enums.WithdrawStatusEnum;
import com.dag.eagleshop.core.account.service.AccountManager;
import com.enation.app.javashop.core.aftersale.model.dto.ClaimSkusDTO;
import com.enation.app.javashop.core.aftersale.model.enums.RefundStatusEnum;
import com.enation.app.javashop.core.aftersale.model.vo.*;
import com.enation.app.javashop.core.aftersale.service.AfterSaleManager;
import com.enation.app.javashop.core.aftersale.service.ClaimsManager;
import com.enation.app.javashop.core.aftersale.service.ExceptionOrderManager;
import com.enation.app.javashop.core.distribution.model.dos.DistributionOrderDO;
import com.enation.app.javashop.core.distribution.service.DistributionOrderManager;
import com.enation.app.javashop.core.goods.model.dos.GoodsSkuDO;
import com.enation.app.javashop.core.goods.model.dto.GoodsQuantityRefreshDTO;
import com.enation.app.javashop.core.goods.model.dto.GoodsQueryParam;
import com.enation.app.javashop.core.goods.model.dto.GoodsSkuDTO;
import com.enation.app.javashop.core.goods.model.vo.SpecValueVO;
import com.enation.app.javashop.core.goods.service.*;
import com.enation.app.javashop.core.member.model.dos.Member;
import com.enation.app.javashop.core.member.service.MemberManager;
import com.enation.app.javashop.core.promotion.shetuan.model.dos.ShetuanDO;
import com.enation.app.javashop.core.promotion.shetuan.model.dos.ShetuanGoodsVO;
import com.enation.app.javashop.core.promotion.shetuan.model.enums.ShetuanGoodsStatusEnum;
import com.enation.app.javashop.core.promotion.shetuan.model.enums.ShetuanStatusEnum;
import com.enation.app.javashop.core.promotion.shetuan.model.vo.QueryShetuanGoodsVO;
import com.enation.app.javashop.core.promotion.shetuan.model.vo.ShetuanOrderVO;
import com.enation.app.javashop.core.promotion.shetuan.service.ShetuanGoodsManager;
import com.enation.app.javashop.core.promotion.shetuan.service.ShetuanManager;
import com.enation.app.javashop.core.promotion.shetuan.service.ShetuanOrderManager;
import com.enation.app.javashop.core.shop.model.vo.ShopCatItem;
import com.enation.app.javashop.core.shop.service.ShopCatManager;
import com.enation.app.javashop.core.system.SystemErrorCode;
import com.enation.app.javashop.core.trade.order.model.dos.OrderDO;
import com.enation.app.javashop.core.trade.order.model.dos.OrderItemsDO;
import com.enation.app.javashop.core.trade.order.model.dto.OrderQueryParam;
import com.enation.app.javashop.core.trade.order.model.dto.ShetuanOrderQueryParam;
import com.enation.app.javashop.core.trade.order.model.vo.OrderLineVO;
import com.enation.app.javashop.core.trade.order.service.OrderOperateManager;
import com.enation.app.javashop.core.trade.order.service.OrderQueryManager;
import com.enation.app.javashop.framework.context.ThreadContextHolder;
import com.enation.app.javashop.framework.database.DaoSupport;
import com.enation.app.javashop.framework.database.Page;
import com.enation.app.javashop.framework.exception.ServiceException;
import com.enation.app.javashop.framework.security.model.Seller;
import com.enation.app.javashop.framework.util.BeanUtil;
import com.enation.app.javashop.framework.util.DateUtil;
import com.enation.app.javashop.framework.util.JsonUtil;
import com.enation.app.javashop.framework.util.StringUtil;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author JFeng
 * @date 2020/7/11 10:48
 */
@Component
@Slf4j
public class ExcelManager {

    @Autowired
    private GoodsQueryManager goodsQueryManager;

    @Autowired
    private GoodsManager goodsManager;

    @Autowired
    private GoodsSkuManager goodsSkuManager;

    @Autowired
    private CategoryManager categoryManager;

    @Autowired
    private ShopCatManager shopCatManager;

    @Autowired
    private OrderQueryManager orderQueryManager;

    @Autowired
    private DistributionOrderManager distributionOrderManager;

    @Autowired
    private MemberManager memberManager;

    @Autowired
    private ShetuanOrderManager shetuanOrderManager;

    @Autowired
    private AfterSaleManager afterSaleManager;

    @Autowired
    private ExceptionOrderManager exceptionOrderManager;

    @Autowired
    private ClaimsManager claimsManager;

    @Autowired
    private ShetuanGoodsManager shetuanGoodsManager;

    @Autowired
    private ShetuanManager shetuanManager;

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    @Qualifier("tradeDaoSupport")
    private DaoSupport daoSupport;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private OrderOperateManager orderOperateManager;
    @Autowired
    private GoodsQuantityManager goodsQuantityManager;
    @Autowired
    private AccountManager accountManager;

    private final String datePartten = "yyyy-MM-dd HH:mm:ss";

    public void importGoods(MultipartFile file) {
        InputStream inputStream = getInputStream(file);
        GoodsDataListener goodsDataListener = new GoodsDataListener(goodsManager, categoryManager, shopCatManager);
        EasyExcel.read(inputStream, GoodsImport.class, goodsDataListener).sheet().doRead();
    }

    private InputStream getInputStream(@RequestParam MultipartFile file) {
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            log.error("上传文件异常");
        }
        return inputStream;
    }


    private InputStream getTemplateFile(String templateFileName) {
        InputStream inputStream = null;
        try {
            URL url = new URL(templateFileName);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            // 设置连接超时时间
            conn.setConnectTimeout(3000);
            inputStream = null;

            // 正常响应时获取输入流, 在这里也就是图片对应的字节流
            if (conn.getResponseCode() == 200) {
                inputStream = conn.getInputStream();
            }
        } catch (IOException e) {
            throw new ServiceException(SystemErrorCode.E930.code(), "导出模板下载失败！");
        }
        return inputStream;
    }

    public void importGoodsSku(MultipartFile file) {
        InputStream inputStream = getInputStream(file);
        SkuDataListener skuDataListener = new SkuDataListener(goodsSkuManager);
        EasyExcel.read(inputStream, SkuImport.class, skuDataListener).sheet().doRead();
    }

    public void importGoodsQuantity(MultipartFile file) {
        InputStream inputStream = getInputStream(file);
        SkuQuantityDataListener skuQuantityDataListener = new SkuQuantityDataListener(goodsQuantityManager);
        EasyExcel.read(inputStream, GoodsQuantityRefreshDTO.class, skuQuantityDataListener).sheet().doRead();
    }

    /**
     * 导入异常单
     *
     * @param file 文件
     */
    public void importExceptionOrder(MultipartFile file) {
        InputStream inputStream = getInputStream(file);
        ExceptionOrderDataListener exceptionOrderDataListener = new ExceptionOrderDataListener(exceptionOrderManager);
        //ExceptionOrderImport未修改
        EasyExcel.read(inputStream, ExceptionOrderImport.class, exceptionOrderDataListener).sheet().doRead();
    }

    public void exportOrderItems(OrderQueryParam orderQueryParam) {
        // 查询订单
        Page page = orderQueryManager.listDistributionOrder(orderQueryParam);
        List<OrderLineVO> orderList = page.getData();
        Map<String, OrderLineVO> orderIndex = Maps.newHashMap();
        List<String> orderSns = new ArrayList<>();
        for (OrderLineVO orderLineVO : orderList) {
            orderSns.add(orderLineVO.getSn());
            orderIndex.put(orderLineVO.getSn(), orderLineVO);
        }
        List<OrderItemsDO> orderItems = orderQueryManager.getOrderItems(orderSns);
        List<Integer> skuIds = orderItems.stream().map(OrderItemsDO::getProductId).collect(Collectors.toList());
        List<GoodsSkuDTO> skuDetails = goodsSkuManager.getSkuList(skuIds);
        Map<Integer, GoodsSkuDTO> skuIndex = skuDetails.stream().collect(Collectors.toMap(GoodsSkuDTO::getSkuId, Function.identity()));
        // 数据转换
        List<ExportOrderSkuVO> exportOrderItems = new ArrayList<>();
        for (OrderItemsDO orderItemsDO : orderItems) {
//            OrderDO orderDO = orderIndex.get(orderItemsDO.getOrderSn());
            OrderLineVO orderLineVO = orderIndex.get(orderItemsDO.getOrderSn());
            GoodsSkuDTO goodsSkuDTO = skuIndex.get(orderItemsDO.getProductId());
            ExportOrderSkuVO exportOrderSkuVO = new ExportOrderSkuVO();
            BeanUtil.copyProperties(orderLineVO, exportOrderSkuVO);
            exportOrderSkuVO.transStatus(orderLineVO);
            if (orderLineVO.getShipAddr() != null) {
                exportOrderSkuVO.setShipAddr(orderLineVO.getShipProvince() + orderLineVO.getShipCity() + orderLineVO.getShipCounty() + orderLineVO.getShipAddr());
            }
            exportOrderSkuVO.setGoodsId(orderItemsDO.getGoodsId());
            exportOrderSkuVO.setSkuId(orderItemsDO.getProductId());
            exportOrderSkuVO.setNum(orderItemsDO.getNum());
            exportOrderSkuVO.setName(orderItemsDO.getName());
            exportOrderSkuVO.setShippingAmount(orderLineVO.getShippingPrice());
            // exportOrderSkuVO.setPurchasePrice(orderItemsDO.getRefundPrice());
            // exportOrderSkuVO.setOriginalPrice(orderItemsDO.getPrice());
            exportOrderSkuVO.setPurchasePrice(orderItemsDO.getPrice());
            if (goodsSkuDTO != null) {
                exportOrderSkuVO.setOriginalPrice(goodsSkuDTO.getCost());
                exportOrderSkuVO.setUpSkuId(goodsSkuDTO.getUpSkuId());
                exportOrderSkuVO.setSupplierName(goodsSkuDTO.getSupplierName());
                exportOrderSkuVO.setUpGoodsId(goodsSkuDTO.getUpGoodsId());
            }
            if (!StringUtils.isEmpty(orderItemsDO.getSpecJson())) {
                String specValues = getSpecValues(orderItemsDO);
                exportOrderSkuVO.setSkuName(specValues);
            }

            exportOrderItems.add(exportOrderSkuVO);
        }

        // 1.查询装卸费明细
        HttpServletResponse response = getResponse("订单明细列表");

        // 输出
        try {
            EasyExcel.write(response.getOutputStream(), ExportOrderSkuVO.class).sheet("sku订单列表").doWrite(exportOrderItems);
        } catch (IOException e) {
            throw new ServiceException("500", "导出异常");
        }
    }

    public void exportSellerOrderItems(OrderQueryParam orderQueryParam) {
        // 查询订单
        Page page = orderQueryManager.listDistributionOrder(orderQueryParam);
        List<OrderLineVO> orderList = page.getData();
        Map<String, OrderLineVO> orderIndex = Maps.newHashMap();
        List<String> orderSns = new ArrayList<>();
        for (OrderLineVO orderLineVO : orderList) {
            orderSns.add(orderLineVO.getSn());
            orderIndex.put(orderLineVO.getSn(), orderLineVO);
        }
        List<OrderItemsDO> orderItems = orderQueryManager.getOrderItems(orderSns);
        List<Integer> skuIds = orderItems.stream().map(OrderItemsDO::getProductId).collect(Collectors.toList());
        List<GoodsSkuDTO> skuDetails = goodsSkuManager.getSkuList(skuIds);
        Map<Integer, GoodsSkuDTO> skuIndex = skuDetails.stream().collect(Collectors.toMap(GoodsSkuDTO::getSkuId, Function.identity()));
        // 数据转换
        List<ExportSellerOrderSkuVO> exportSellerOrderItems = new ArrayList<>();
        for (OrderItemsDO orderItemsDO : orderItems) {
            OrderLineVO orderLineVO = orderIndex.get(orderItemsDO.getOrderSn());
            GoodsSkuDTO goodsSkuDTO = skuIndex.get(orderItemsDO.getProductId());
            ExportSellerOrderSkuVO exportSellerOrderSkuVO = new ExportSellerOrderSkuVO();
            BeanUtil.copyProperties(orderLineVO, exportSellerOrderSkuVO);
            exportSellerOrderSkuVO.transStatus(orderLineVO);
            if (orderLineVO.getShipAddr() != null) {
                exportSellerOrderSkuVO.setShipAddr(orderLineVO.getShipProvince() + orderLineVO.getShipCity() + orderLineVO.getShipCounty() + orderLineVO.getShipAddr());
            }
            exportSellerOrderSkuVO.setGoodsId(orderItemsDO.getGoodsId());
            exportSellerOrderSkuVO.setSkuId(orderItemsDO.getProductId());
            exportSellerOrderSkuVO.setNum(orderItemsDO.getNum());
            exportSellerOrderSkuVO.setName(orderItemsDO.getName());
            exportSellerOrderSkuVO.setShippingAmount(orderLineVO.getShippingPrice());
            exportSellerOrderSkuVO.setPurchasePrice(orderItemsDO.getPrice());
            if (goodsSkuDTO != null) {
                exportSellerOrderSkuVO.setOriginalPrice(goodsSkuDTO.getCost());
                exportSellerOrderSkuVO.setUpSkuId(goodsSkuDTO.getUpSkuId());
                exportSellerOrderSkuVO.setSupplierName(goodsSkuDTO.getSupplierName());
                exportSellerOrderSkuVO.setUpGoodsId(goodsSkuDTO.getUpGoodsId());
            }
            if (!StringUtils.isEmpty(orderItemsDO.getSpecJson())) {
                String specValues = getSpecValues(orderItemsDO);
                exportSellerOrderSkuVO.setSkuName(specValues);
            }

            exportSellerOrderItems.add(exportSellerOrderSkuVO);
        }

        // 1.查询装卸费明细
        HttpServletResponse response = getResponse("商户端订单明细列表");

        // 输出
        try {
            EasyExcel.write(response.getOutputStream(), ExportSellerOrderSkuVO.class).sheet("sku订单列表").doWrite(exportSellerOrderItems);
        } catch (IOException e) {
            throw new ServiceException("500", "导出异常");
        }
    }

    public void exportGoodsSkuList(GoodsQueryParam goodsQueryParam) {
        // 查询商品
        Page goodsPage = goodsQueryManager.list(goodsQueryParam);
        List<Map> goodsList = goodsPage.getData();
        List<Integer> goodsIds = new ArrayList<>();
        Map<Integer, Map> goodsIndex = Maps.newHashMap();
        for (Map goods : goodsList) {
            Integer goods_id = Integer.valueOf(goods.get("goods_id").toString());
            goodsIds.add(goods_id);
            String categoryPath = goodsQueryManager.queryCategoryPath(Integer.valueOf(goods.get("category_id").toString()));
            goods.put("category_name", categoryPath);
            goodsIndex.put(goods_id, goods);
        }

        // 查询商品规格
        List<GoodsSkuDO> goodsSkuDOS = goodsSkuManager.listByGoodsIds(goodsIds);
        List<ExportGoodsSkuVO> exportGoodsSkuVOS = new ArrayList<>();
        for (GoodsSkuDO goodsSkuDO : goodsSkuDOS) {
            Map goods = goodsIndex.get(goodsSkuDO.getGoodsId());

            ExportGoodsSkuVO exportGoodsSkuVO = new ExportGoodsSkuVO(goods, goodsSkuDO);
            exportGoodsSkuVOS.add(exportGoodsSkuVO);
        }

        HttpServletResponse response = getResponse("商品规格列表");

        // 输出
        try {
            EasyExcel.write(response.getOutputStream(), ExportGoodsSkuVO.class).sheet("商品列表").doWrite(exportGoodsSkuVOS);
        } catch (IOException e) {
            throw new ServiceException("500", "导出异常");
        }
    }

    public void groupPurchaseExport(ShetuanOrderQueryParam shetuanOrderQueryParam) {
        // 查询社区团购订单
        Page page = shetuanOrderManager.queryPage(shetuanOrderQueryParam);
        List<ShetuanOrderVO> shetuanList = page.getData();
        Map<String, ShetuanOrderVO> orderIndex = Maps.newHashMap();
        //订单号集合
        List<String> orderSns = new ArrayList<>();
        //key：订单编号 value：社团订单每条记录的数据
        List<Integer> leaderMemberIds = new ArrayList<>();

        for (ShetuanOrderVO shetuanOrder : shetuanList) {
            orderSns.add(shetuanOrder.getSn());
            orderIndex.put(shetuanOrder.getSn(), shetuanOrder);
            leaderMemberIds.add(shetuanOrder.getLeaderMemberId());
        }
        List<OrderDO> orderList = orderQueryManager.loadOrderList(orderSns);
        Map<String, OrderDO> orderDo = orderList.stream().collect(Collectors.toMap(OrderDO::getSn, Function.identity()));
        // 查询订单货物
        List<OrderItemsDO> orderItems = orderQueryManager.getOrderItems(orderSns);

        //  查询商品
        List<Integer> skuIds = orderItems.stream().map(OrderItemsDO::getProductId).collect(Collectors.toList());
        List<GoodsSkuDTO> skuDetails = goodsSkuManager.getSkuList(skuIds);
        Map<Integer, GoodsSkuDTO> skuIndex = skuDetails.stream().collect(Collectors.toMap(GoodsSkuDTO::getSkuId, Function.identity()));
        //查询团长信息
        List<DistributionOrderDO> distributionOrderDOS = distributionOrderManager.loadDistributionOrderList(orderSns);
        Map<String, DistributionOrderDO> distributionIndex = distributionOrderDOS.stream().collect(Collectors.toMap(DistributionOrderDO::getOrderSn, Function.identity()));

        List<Integer> memberIdLv1 = distributionOrderDOS.stream().map(DistributionOrderDO::getMemberIdLv1).collect(Collectors.toList());
        List<Member> memberS = memberManager.loadMemberList(memberIdLv1);
        Map<Integer, Member> memberIndex = memberS.stream().collect(Collectors.toMap(Member::getMemberId, Function.identity()));

        // 数据转换
        List<ExcelGroupVO> excelGroup = new ArrayList<>();
        for (OrderItemsDO orderItemsDO : orderItems) {
            ShetuanOrderVO shetuanOrderDO = orderIndex.get(orderItemsDO.getOrderSn());
            GoodsSkuDTO goodsSkuDTO = skuIndex.get(orderItemsDO.getProductId());
            OrderDO orderDO = orderDo.get(orderItemsDO.getOrderSn());

            ExcelGroupVO excelGroupVO = new ExcelGroupVO();
            BeanUtil.copyProperties(orderDO, excelGroupVO);

            excelGroupVO.transStatus(orderDO);
            excelGroupVO.setGoodsId(orderItemsDO.getGoodsId());

            excelGroupVO.setSkuId(orderItemsDO.getProductId());
            excelGroupVO.setName(orderItemsDO.getName());
            excelGroupVO.setGoodsNum(orderItemsDO.getNum());

            excelGroupVO.setPurchasePrice(orderItemsDO.getRefundPrice());
            excelGroupVO.setOriginalPrice(orderItemsDO.getPrice());

            excelGroupVO.setLeaderName(shetuanOrderDO.getLeaderName());
            excelGroupVO.setLeaderMobile(shetuanOrderDO.getLeaderMobile());
            excelGroupVO.setSiteName(shetuanOrderDO.getSiteName());
            excelGroupVO.setPickAddress(shetuanOrderDO.getPickAddress());

            DistributionOrderDO distributionOrderDO = distributionIndex.get(orderItemsDO.getOrderSn());
            if (distributionOrderDO != null) {
                Member member = memberIndex.get(distributionOrderDO.getMemberIdLv1());
                if (member != null) {
                    excelGroupVO.setRealName(member.getRealName());
                    excelGroupVO.setRealMobile(member.getMobile());
                }
            }
            if (goodsSkuDTO != null) {
                excelGroupVO.setUpSkuId(goodsSkuDTO.getUpSkuId());
                excelGroupVO.setSupplierName(goodsSkuDTO.getSupplierName());
                excelGroupVO.setUpGoodsId(goodsSkuDTO.getUpGoodsId());
            }
            if (StringUtil.notEmpty(orderItemsDO.getSpecJson())) {
                String specValues = getSpecValues(orderItemsDO);
                excelGroupVO.setSkuName(specValues);
            }

            excelGroup.add(excelGroupVO);
        }

        // 1.查询装卸费明细
        HttpServletResponse response = getResponse("社团订单明细");

        // 输出
        try {
            EasyExcel.write(response.getOutputStream(), ExcelGroupVO.class).sheet("订单列表").doWrite(excelGroup);
        } catch (IOException e) {
            throw new ServiceException("500", "导出异常");
        }
    }

    private String getSpecValues(OrderItemsDO orderItemsDO) {
        String specValues = "";
        List<SpecValueVO> specValueVOS = JsonUtil.jsonToList(orderItemsDO.getSpecJson(), SpecValueVO.class);
        if (CollectionUtils.isEmpty(specValueVOS)) {
            return "";
        }
        for (SpecValueVO specValueVO : specValueVOS) {
            specValues += specValueVO.getSpecValue() + ";";
        }
        return specValues;
    }

    private HttpServletResponse getResponse(String fileName) {
        HttpServletResponse response = ThreadContextHolder.getHttpResponse();
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        return response;
    }

    /**
     * 退补差价单Excel导出
     *
     * @param spreadRefundQueryParamVO 退补单查询实体
     */
    public void spreadRefundExport(SpreadRefundQueryParamVO spreadRefundQueryParamVO) {
        //查询分页对象
        Page<SpreadRefundQueryParamVO> page = afterSaleManager.querySpreadRefund(spreadRefundQueryParamVO);
        List<SpreadRefundQueryParamVO> data = page.getData();
        List<ExportSpreadRefundVO> exportSpreadRefundVOList = new ArrayList<>();
        for (SpreadRefundQueryParamVO spreadRefund : data) {
            //查询订单中的商品
            List<OrderItemsDO> orderItems = orderQueryManager.getOrderItems(spreadRefund.getOrderSn());
            String goodsNames = "";
            for (int i = 0; i < orderItems.size(); i++) {
                goodsNames = goodsNames.concat(orderItems.get(i).getName());
                if (i < orderItems.size() - 1) {
                    goodsNames = goodsNames.concat(",");
                }
            }
            ExportSpreadRefundVO exportSpreadRefundVO = new ExportSpreadRefundVO();
            BeanUtil.copyProperties(spreadRefund, exportSpreadRefundVO);
            exportSpreadRefundVO.setRefundStatus(RefundStatusEnum.valueOf(spreadRefund.getRefundStatus()).description());
            exportSpreadRefundVO.setGoodsNames(goodsNames);
            exportSpreadRefundVOList.add(exportSpreadRefundVO);
        }
        HttpServletResponse response = getResponse("退款单明细表");
        // 输出
        try {
            EasyExcel.write(response.getOutputStream(), ExportSpreadRefundVO.class).sheet("退款单列表").doWrite(exportSpreadRefundVOList);
        } catch (IOException e) {
            throw new ServiceException("500", "导出异常");
        }
    }

    /**
     * 异常单条件查询后导出Excel
     *
     * @param exceptionQueryParamVO 异常单查询实体
     */
    public void exceptionOrderExport(ExceptionQueryParamVO exceptionQueryParamVO) {
        //1.条件查询异常单数据
        Page<ExceptionOrderVO> page = exceptionOrderManager.pageExceptionOrder(exceptionQueryParamVO);
        List<ExceptionOrderVO> ExceptionOrderVOList = page.getData();
        List<ExportExceptionOrderVO> exportList = new ArrayList<>();
        //2.将数据转换成导出用的实体
        for (ExceptionOrderVO exceptionOrder : ExceptionOrderVOList) {
            ExportExceptionOrderVO export = new ExportExceptionOrderVO();
            BeanUtil.copyProperties(exceptionOrder, export);
            //时间转换 秒时间戳转 yyyy-MM-dd HH:mm:ss
            Long reciveTime = exceptionOrder.getReciveTime();
            if (!ObjectUtils.isEmpty(reciveTime)) {
                export.setReciveTime(DateUtil.toString(reciveTime, this.datePartten));
            }
            Long createTime = exceptionOrder.getCreateTime();
            if (!ObjectUtils.isEmpty(createTime)) {
                export.setCreateTime(DateUtil.toString(createTime, this.datePartten));
            }
            Long processTime = exceptionOrder.getProcessTime();
            if (!ObjectUtils.isEmpty(processTime)) {
                export.setProcessTime(DateUtil.toString(processTime, this.datePartten));
            }
            Long completeTime = exceptionOrder.getCompleteTime();
            if (!ObjectUtils.isEmpty(completeTime)) {
                export.setCompleteTime(DateUtil.toString(completeTime, this.datePartten));
            }
            Long finishTime = exceptionOrder.getFinishTime();
            if (!ObjectUtils.isEmpty(finishTime)) {
                export.setFinishTime(DateUtil.toString(finishTime, this.datePartten));
            }
            exportList.add(export);
        }
        HttpServletResponse response = getResponse("异常单明细表");
        // 3.输出
        try {
            EasyExcel.write(response.getOutputStream(), ExportExceptionOrderVO.class).sheet("异常单列表").doWrite(exportList);
        } catch (IOException e) {
            throw new ServiceException("500", "导出异常");
        }
    }

    /**
     * 导出理赔单明细
     *
     * @param claimsQueryVO
     */
    public void claimsExport(ClaimsQueryVO claimsQueryVO, Seller seller) {
        //1.条件查询异常单数据
        Page<ClaimsVO> page = claimsManager.getClaimsList(claimsQueryVO, seller);
        List<ClaimsVO> claimsVOList = page.getData();
        List<ExportClaimsVO> exportClaimsVOList = new ArrayList<>();
        //2.将数据转换成导出用的实体
        for (ClaimsVO claimsVO : claimsVOList) {
            ExportClaimsVO export = new ExportClaimsVO();
            BeanUtil.copyProperties(claimsVO, export);
            //时间转换 秒时间戳转 yyyy-MM-dd HH:mm:ss
            //申请时间
            Long applyTime = claimsVO.getApplyTime();
            if (!ObjectUtils.isEmpty(applyTime)) {
                export.setApplyTime(DateUtil.toString(applyTime, this.datePartten));
            }
            //审核时间
            Long auditTime = claimsVO.getAuditTime();
            if (!ObjectUtils.isEmpty(auditTime)) {
                export.setApplyTime(DateUtil.toString(auditTime, this.datePartten));
            }
            //理赔时间
            Long claimTime = claimsVO.getClaimTime();
            if (!ObjectUtils.isEmpty(claimTime)) {
                export.setClaimTime(DateUtil.toString(claimTime, this.datePartten));
            }
            //封装sku信息，商品名*赠送（补发）数量
            List<ClaimSkusDTO> skusDTOList = JSON.parseObject(claimsVO.getClaimSkus(), new TypeReference<List<ClaimSkusDTO>>() {
            });
            String claimSkus = "";
            if (!CollectionUtils.isEmpty(skusDTOList)) {
                for (ClaimSkusDTO sku : skusDTOList) {
                    claimSkus = claimSkus.concat(sku.getGoodsName() + "*" + sku.getNum() + ";");
                }
            }
            export.setClaimSkus(claimSkus);
            exportClaimsVOList.add(export);
        }
        HttpServletResponse response = getResponse("理赔单明细表");
        // 3.输出
        try {
            EasyExcel.write(response.getOutputStream(), ExportClaimsVO.class).sheet("理赔单明细表").doWrite(exportClaimsVOList);
        } catch (IOException e) {
            throw new ServiceException("500", "导出理赔单异常");
        }
    }

    /**
     * 导出社团商品明细
     */
    public void shetuanGoodsExport(QueryShetuanGoodsVO queryShetuanGoodsVO, Seller seller) {
        //团购状态
        ShetuanDO shetuanDO = shetuanManager.getShetuanById(queryShetuanGoodsVO.getShetuanId());
        String shetuanStatusText = ShetuanStatusEnum.getTextByIndex(shetuanDO.getStatus());

        Page<ShetuanGoodsVO> page = shetuanGoodsManager.queryByPage(queryShetuanGoodsVO);
        List<ShetuanGoodsVO> goodsList = page.getData();
        List<ExcelShetuanGoodsVO> excelShetuanGoodsVOList = new ArrayList<>();
        for (ShetuanGoodsVO shetuanGoodsVO : goodsList) {
            ExcelShetuanGoodsVO excelVO = new ExcelShetuanGoodsVO();
            excelVO.setShetuanId(shetuanGoodsVO.getShetuanId());
            excelVO.setShetuanName(shetuanDO.getShetuanName());
            excelVO.setShetuanStatusText(shetuanStatusText);
            excelVO.setShetuanGoodsStatusText(ShetuanGoodsStatusEnum.getTextByIndex(shetuanGoodsVO.getStatus()));
            excelVO.setShopName(seller.getSellerName());
            excelVO.setSkuId(shetuanGoodsVO.getSkuId());
            excelVO.setGoodsName(shetuanGoodsVO.getGoodsName());
            if (StringUtils.isNotEmpty(shetuanGoodsVO.getShopCatItems())) {
                List<ShopCatItem> shopCatItems = JSON.parseArray(shetuanGoodsVO.getShopCatItems(), ShopCatItem.class);
                List<String> shopCatPathNames = shopCatItems.stream().map(ShopCatItem::getCatPathName).collect(Collectors.toList());
                excelVO.setShopCatName(StringUtil.implode(";", shopCatPathNames.toArray()));
            }
            excelVO.setPriority(shetuanGoodsVO.getPriority());
            excelVO.setCost(shetuanGoodsVO.getCost());
            excelVO.setOriginPrice(shetuanGoodsVO.getOriginPrice());
            excelVO.setSalesPrice(shetuanGoodsVO.getSalesPrice());
            excelVO.setShetuanPrice(shetuanGoodsVO.getShetuanPrice());
            excelVO.setGoodsNum(shetuanGoodsVO.getGoodsNum());
            excelVO.setVisualNum(shetuanGoodsVO.getVisualNum());
            excelVO.setLimitNum(shetuanGoodsVO.getLimitNum());
            excelVO.setFirstRate(shetuanGoodsVO.getFirstRate());
            excelVO.setSecondRate(shetuanGoodsVO.getSecondRate());
            excelVO.setSelfRaisingRate(shetuanGoodsVO.getSelfRaisingRate());
            excelVO.setInviteRate(shetuanGoodsVO.getInviteRate());
            excelShetuanGoodsVOList.add(excelVO);
        }
        HttpServletResponse response = getResponse("社团商品明细表");
        // 3.输出
        try {
            String templateFileName = "https://egale-shop.oss-cn-hangzhou.aliyuncs.com/excel/%E7%A4%BE%E5%9B%A2%E5%95%86%E5%93%81%E6%98%8E%E7%BB%86%E8%A1%A8.xlsx";
            InputStream file = getTemplateFile(templateFileName);
            EasyExcel.write(response.getOutputStream()).withTemplate(file).sheet().doWrite(excelShetuanGoodsVOList);
        } catch (IOException e) {
            log.error("上传文件异常", e);
            throw new ServiceException("500", "导出社团商品明细表异常");
        }
    }

    //导入社团商品详情
    public void importShetuanGoods(MultipartFile file) {
        // 1、读取文件，保存商品
        InputStream inputStream = getInputStream(file);
        ShetuanGoodsDataListener shetuanGoodsDataListener =
                new ShetuanGoodsDataListener(goodsSkuManager, shopCatManager, amqpTemplate, daoSupport, jdbcTemplate);
        EasyExcel.read(inputStream, ExcelShetuanGoodsVO.class, shetuanGoodsDataListener).sheet().doRead();

        // 2.输出保存出错的商品明细
        List<ExcelShetuanGoodsVO> errorImportList = ShetuanGoodsDataListener.errorImportList;
        if (!CollectionUtils.isEmpty(errorImportList)) {
            HttpServletResponse response = getResponse("社团商品保存出错的商品明细表");
            try {
                String templateFileName = "https://egale-shop.oss-cn-hangzhou.aliyuncs.com/excel/%E7%A4%BE%E5%9B%A2%E5%95%86%E5%93%81%E6%98%8E%E7%BB%86%E8%A1%A8.xlsx";
                InputStream templateFile = getTemplateFile(templateFileName);
                EasyExcel.write(response.getOutputStream()).withTemplate(templateFile).sheet().doWrite(errorImportList);
                ShetuanGoodsDataListener.errorImportList.clear();
            } catch (IOException e) {
                throw new ServiceException("500", "社团商品保存出错的商品明细表");
            }
        }
    }

    //导入订单（包含商城和团购），批量发货（循环调用发货方法）
    public void shipOrderImport(MultipartFile file) {
        InputStream inputStream = getInputStream(file);
        ShipOrderDataListener shipOrderDataListener = new ShipOrderDataListener(orderOperateManager, daoSupport);

        EasyExcel.read(inputStream, ShipOrderImport.class, shipOrderDataListener).sheet().doRead();

        //发货失败的列表
        List<ShipOrderImport> errorList = shipOrderDataListener.errorList;
        if (!CollectionUtils.isEmpty(errorList)) {
            HttpServletResponse response = getResponse("发货失败的订单");
            try {
                EasyExcel.write(response.getOutputStream(), ShipOrderImport.class).sheet("发货失败的订单").doWrite(errorList);
                shipOrderDataListener.errorList.clear();
            } catch (Exception e) {
                throw new ServiceException("604", "导出发货失败的订单出错");
            }
        }
    }

    // 导出提现单
    public void withdrawBillExport(PageDTO<QueryWithdrawBillDTO> pageDTO) {
        // 1、查询数据
        ViewPage<WithdrawBillDTO> withdrawBillDTOViewPage = accountManager.queryWithdrawList(pageDTO);
        List<WithdrawBillDTO> withdrawBillDTOList = withdrawBillDTOViewPage.getRecords();

        // 封装需要导出的数据
        List<ExcelWithdrawBill> excelBillList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(withdrawBillDTOList)) {
            for (int i = 0; i < withdrawBillDTOList.size(); i++) {
                WithdrawBillDTO withdrawBillDTO = JSON.parseObject(JSON.toJSON(withdrawBillDTOList.get(i)).toString(), new TypeReference<WithdrawBillDTO>() {
                });
                ExcelWithdrawBill excelBill = new ExcelWithdrawBill();
                BeanUtil.copyProperties(withdrawBillDTO, excelBill);


                // 申请时间  转换时间格式
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                excelBill.setApplyTimeString(simpleDateFormat.format(withdrawBillDTO.getApplyTime()));

                // 处理用户类型  【用户】心琴悠扬
                String memberName = withdrawBillDTO.getMemberName();
                int subLast = memberName.indexOf("】");
                if (subLast > 0) {
                    excelBill.setMemberType(memberName.substring(1, subLast));
                }

                excelBill.setMemberName(memberName.substring(subLast + 1));

                // 提现方式
                Integer withdrawChannel = withdrawBillDTO.getWithdrawChannel();
                excelBill.setWithdrawChannelName(TradeChannelEnum.getTextByIndex(withdrawChannel));


                // 提现账户及账户名（银行卡及其它方式取不同的字段）
                String accountName = withdrawBillDTO.getOtherAccountName();
                String accountNo = withdrawBillDTO.getOtherAccountNo();
                if (TradeChannelEnum.ACCOUNT.getIndex() == withdrawChannel) {
                    accountName = withdrawBillDTO.getOpenAccountName();
                    accountNo = withdrawBillDTO.getCardNo();
                }
                excelBill.setAccountName(accountName);
                excelBill.setAccountNo(accountNo);

                excelBill.setStatusText(WithdrawStatusEnum.getTextByIndex(withdrawBillDTO.getStatus()));
                excelBillList.add(excelBill);
            }
        }

        HttpServletResponse response = getResponse("提现单明细表");
        // 3.输出
        try {
            EasyExcel.write(response.getOutputStream(), ExcelWithdrawBill.class).sheet("提现单明细表").doWrite(excelBillList);
        } catch (IOException e) {
            throw new ServiceException("500", "导出提现单异常");
        }
    }
}
